package com.kelw.controller;

import com.kelw.dto.LoginDto;
import com.kelw.dto.RegisterDto;
import com.kelw.dto.UpdateUserInfoDto;
import com.kelw.service.MsmService;
import com.kelw.service.UserRoleService;
import com.kelw.service.UserService;
import com.kelw.utils.JwtUtils;
import com.kelw.utils.RandomUtil;
import com.kelw.vo.CommonResult;
import com.kelw.vo.TokenVo;
import com.kelw.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.concurrent.TimeUnit;

import static com.kelw.vo.UserVo.fromUser;

@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/common")
@Api(tags = "(学生,教师,管理员)通用相关接口")
public class CommonController {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/error")
    public CommonResult<String> error() {
        return CommonResult.<String>builder()
                .code(233)
                .message("请求错误!")
                .build();
    }

    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "系统用户实体", required = true, dataType = "user", paramType = "body")
    })
    public CommonResult<String> Register(@RequestBody @Valid RegisterDto registerDto) {
        return CommonResult.<String>builder()
                .data(userService.register(registerDto))
                .build();
    }

    @ApiOperation("发送手机验证码")
    @GetMapping("send/{phone}")
    public CommonResult<String> sendCode(@PathVariable String phone){
        //从Redis获取验证码，如果获取到，返回ok
        //key 手机号   value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return CommonResult.<String>builder()
                    .build();
        }
        //如果从Redis获取不到
        //生成验证码，
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.send(phone,code);
        //生成验证码放到Redis里面，设置有效时间
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,100, TimeUnit.DAYS);
            return CommonResult.<String>builder()
                    .build();
        }else {
            return CommonResult.<String>builder()
                    .data("发送短信失败")
                    .build();
        }
    }

    @ApiOperation("手机号是否注册查询接口")
    @GetMapping("/check/{phone}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "string", paramType = "path")
    })
    public CommonResult<Boolean> checkUsername(@PathVariable(value = "phone") String phone) {
        return CommonResult.<Boolean>builder()
                .data(userService.checkPhone(phone))
                .build();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "string", paramType = "body"),
            @ApiImplicitParam(name = "password", value = "系统用户密码", required = true, dataType = "string", paramType = "body"),
    })
    public CommonResult<String> login(@RequestBody @Valid LoginDto loginDto) {
        return CommonResult.<String>builder()
                .data(userService.login(loginDto))
                .build();
    }

    @GetMapping("/getMenu")
    @ApiOperation(value = "获取不同用户的权限菜单")
    public CommonResult<String> getMenu(HttpServletRequest request) {
        return CommonResult.<String>builder()
                .data(userRoleService.getMenuInfo(JwtUtils.getUserInfoByToken(request).getRoleId()))
                .build();
    }

    @GetMapping("/checkToken")
    @ApiOperation("验证用户token接口")
    public CommonResult<TokenVo> checkToken(HttpServletRequest request) {
        return CommonResult.<TokenVo>builder()
                .data(JwtUtils.getUserInfoByToken(request))
                .build();
    }

    @GetMapping("/getCurrentUser")
    @ApiOperation("供给普通用户查询个人信息使用")
    public CommonResult<UserVo> getCurrentUser(HttpServletRequest request) {
        return CommonResult.<UserVo>builder()
                .data(fromUser(userService.getUserByUsername(JwtUtils.getUserInfoByToken(request).getPhone())))
                .build();
    }

    @GetMapping("/getCurrentRoleId")
    @ApiOperation("供给普通用户查询个人信息使用1")
    public CommonResult<Integer> getCurrentRoleId(HttpServletRequest request) {
        Integer roleId = JwtUtils.getUserInfoByToken(request).getRoleId();
        return CommonResult.<Integer>builder()
                .data(roleId)
                .build();
    }
    @PostMapping("/updateCurrentUser")
    @ApiOperation("供给用户更改个人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "系统用户实体", required = true, dataType = "user", paramType = "body")
    })
    public CommonResult<Object> updateCurrentUser(@RequestBody @Valid UpdateUserInfoDto updateUserInfoDto) {
        userService.updateUserInfo(updateUserInfoDto);
        return CommonResult.builder()
                .build();
    }

}
